"""
验证APP Key和Token
"""
# src/core/dependencies.py
from fastapi import Depends, HTTPException, Header
from src.core.security import verify_token, get_app_id
from src.core import retMes,str_utils as strU
from sqlalchemy.orm import Session
from src.core.ormdb import get_db
from src.schemas.login_manager import AuthManager
from pydantic import ValidationError


def auth_api_key(db: Session = Depends(get_db),
                 api_key: str = Header(None, alias="x-api-key"),
                 language: str = Header(None, alias="x-language")):
    # 为了接口命名规范，把API_KEY改为 x-api-key 2025/04/23
    # 为了接口命名规范，把language改为 x-language 2025/10/31
    # 根据 APP KEY 抓取项目配置APP ID request: Request
    # api_key = api_key  api_key: str = Header(None, alias="API_KEY")
    # api_key: str = Header(...) 无法获取，通过 request.headers 获取
    """
     headers = request.headers
    print(headers)
    api_key = headers.get('api-key')
    if api_key is None:
        retMes.Raise(message='API_KEY header is missing').mes()
    """

    app_id, api_name = get_app_id(db, api_key, language)
    # app_id = 1
    return {"app_id": app_id,
            "api_key": api_key,
            "api_name": api_name,
            "language": language}


def auth_token(db: Session = Depends(get_db),
               api_key: str = Header(None, alias="x-api-key"),
               # token: str = Header(None, alias="token"),
               authorization: str = Header(None, alias="authorization"),
               language: str = Header(None, alias="x-language")
               ) -> AuthManager:
    # 为了接口命名规范，把API_KEY改为 x-api-key 2025/04/23
    token = None
    if strU.is_empty(token) and strU.is_not_empty(authorization):
        token = authorization.replace("Bearer ", "") if authorization else None

    payload = verify_token(db, api_key, token, language)
    if not payload:
        msg = retMes.Msg(db, '-1', 9392, language).mes()
        retMes.Raise(message=msg, data=None, status_code=401).mes()
    # raise HTTPException(status_code=401, detail="Invalid or expired JWT Token")
    if payload.get('api_id') != payload.get('app_id'):
        msg = retMes.Msg(db, '-1', 9393, language).mes()
        retMes.Raise(message=msg).mes()

    payload.pop('app_id', None)
    # return payload
    try:
        return AuthManager.model_validate(payload)  # Pydantic v2
        # 如果是 v1 用 AuthManager.parse_obj(payload)
    except ValidationError as e:
        msg = retMes.Msg(db, '-1', 9394, language, e).mes()
        retMes.Raise(message=msg).mes()
